
C# divides the word of types into value types and reference types. Value types are created on the stack. All the intrinsic types like int, long are value types and thus are created on the stack. Object on the other hand are reference types. Reference type are created on an undifferentiated block of memory known as the heap. Value type store the value into memory and reference type store the address of the value into memory. Given bellow the example code and explain the code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using testForClass1;
namespace testFor
{
public class myValue
{
public int _firstValue;
}
public class Program
{
static void Main(string[] args)
{
// Value Type
int _firstValue = 10;
int _secondValue = 50;
Console.WriteLine("My 1st value is : " + _firstValue + " My 2nd value is : " + _secondValue);
_firstValue = _secondValue;
Console.WriteLine("My 1st value is : " + _firstValue + " My 2nd value is : " + _secondValue);
// reference Type
myValue obj = new myValue();
obj._firstValue = 10;
myValue obj2 = obj;
Console.WriteLine("My 1st value is : " + obj._firstValue + " My 2nd value is : " + obj2._firstValue);
obj2._firstValue = 100;
Console.WriteLine("My 1st value is : " + obj._firstValue + " My 2nd value is : " + obj2._firstValue);
Console.Read();
}
}
}
First, we create a int type variables but when we change the value to replace another value it copy of the second variables value change. Now we see the class object and assign the object value and then create the second object of the same class and replace the first object value to second object value. We can see the reflection of the two objects because this is the reference type.